package com.gin.kotlin.no_gay_alliance.worker

import android.content.Context
import android.util.Log
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.gin.kotlin.no_gay_alliance.activity.NoticeActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.NotificationUtils
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.database.entity.NoticeMsg
import com.gin.kotlin.no_gay_alliance.enums.NotificationType
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.NoticeProvider
import java.util.concurrent.TimeUnit

/**
 * 更新提醒消息的任务
 * @constructor
 */
class NoticeUpdateWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    private val TAG = this::class.java.simpleName
    override fun doWork(): Result {
        Log.d(TAG, "后台更新提醒消息")
        NoticeProvider.getInstance().enqueue(callback = object : RCallback<List<NoticeMsg>, Nothing> {
            override fun onSuccess(data: List<NoticeMsg>, ignoreCache: Boolean) {
                val unreadCount = data.count { it.unread }
                if (unreadCount > 0) {
                    App.INSTANCE.notify(NotificationType.NOTICE,"你有 $unreadCount 条未读消息",NoticeActivity::class.java)
                } else {
                    NotificationUtils.cancel(applicationContext, NotificationType.NOTICE.ordinal)
                }
            }

            override fun onError(errorMessage: String) {
                Log.w(TAG, "onError: $errorMessage")
            }
        })
        // 再次启动
        start()

        return Result.success()
    }

    companion object {
        fun start(delaySeconds: Long = 60) {
            val manager = WorkManager.getInstance(App.INSTANCE)
            // 清空相同任务
            manager.cancelAllWorkByTag(NoticeUpdateWorker::class.java.name)
            // 构造任务请求
            // 任务限制：必须联网
            val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
            // 一次性任务
            val workRequest = OneTimeWorkRequest.Builder(NoticeUpdateWorker::class.java)
                .setConstraints(constraints)
                // 执行延迟
                .setInitialDelay(delaySeconds, TimeUnit.SECONDS)
                // 重试策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, WorkRequest.MIN_BACKOFF_MILLIS, TimeUnit.MILLISECONDS)
                .build()
            // 提交任务
            manager.enqueue(workRequest)
        }
    }
}